package com.rocker.client.controller;

import com.rocker.client.produce.ClientProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author 喻湘东
 * @Create 2019-11-22 23:21:15
 */
@RestController
@Slf4j
public class ClientController {

    @Autowired
    private ClientProducer clientProducer;


    @GetMapping("/buy")
    public String createOrder(HttpServletRequest request) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        String sessionId = getValue(request.getCookies(), "create_order_cookie");

        String msg = "创建订单|"+sessionId;
        Message message = new Message("rocker-client", "create_order", msg.getBytes());
        clientProducer.getProducer().send(message);
        log.info("客户端消息发送成功");
        return "下单成功";
    }

    protected String getValue(Cookie[] cookies, String key) {
        String value = null;
        if (null != cookies && cookies.length > 0) {
            for (Cookie c : cookies) {
                if (key.equals(c.getName())) {
                    value = c.getValue();
                    break;
                }
            }
        }

        return value;
    }

}
